package com.cn.kabalifeuser.ui.service.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.cn.kabalifeuser.R;
import com.cn.kabalifeuser.base.IBaseActivity;
import com.cn.kabalifeuser.config.CustomRefreshListener;
import com.cn.kabalifeuser.config.LoginHelper;
import com.cn.kabalifeuser.config.RefreshHelper;
import com.cn.kabalifeuser.ui.my.adapter.AddressCheckAdapter;
import com.cn.kabalifeuser.ui.my.bean.AddressProvinceListBean;
import com.cn.kabalifeuser.ui.my.bean.CooperationSreviceListBean;
import com.cn.kabalifeuser.ui.service.adapter.MerchantsListAdapter;
import com.cn.kabalifeuser.ui.service.adapter.SreviceTypeToAdapter;
import com.cn.kabalifeuser.ui.service.adapter.TypeLeftBusinessAdapter;
import com.cn.kabalifeuser.ui.service.adapter.TypeRightBusinessAdapter;
import com.cn.kabalifeuser.ui.service.bean.BusinessListBean;
import com.cn.kabalifeuser.utils.LoggerUtils;
import com.cn.kabalifeuser.utils.RxToast;
import com.cn.kabalifeuser.view.NotDataView;
import com.cn.kabalifeuser.view.PopupWindow.CommonPopupWindow;
import com.cn.kabalifeuser.view.PopupWindow.CommonUtil;
import com.cn.kabalifeuser.view.xx.MyRatingBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.w3c.dom.Element;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 晓林 on 2020/9/10.
 * function: 商户列表
 */
public class MerchantsListActivity extends IBaseActivity<MerchantsListView, MerchantsListPresenter> implements MerchantsListView, CommonPopupWindow.ViewInterface {
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_region)
    TextView tvRegion;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.rv_notice)
    RecyclerView rvNotice;
    @BindView(R.id.img_check)
    ImageView imgCheck;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;

    @BindView(R.id.tv_types)
    RecyclerView tvTypes;
    List<CooperationSreviceListBean.ResultBean> mListRight;
    TypeRigthBusinessAdapter typeRightAdapter;


    List<BusinessListBean.ResultBean.DataBean> mList;
    MerchantsListAdapter mAdapter;
    private View notDataView;

    Bundle bundle;
    private int cityID;
    private int areaID;
    private int service_type = 0;
    private int sign;


    int checkSign = 1; //1:综合2：区域 3：评分 4：类目
    int fractionChek = 1;


    CooperationSreviceListBean cooperationSreviceListBean;


    private CommonPopupWindow popupWindowAddress;
    List<AddressProvinceListBean.ResultBean> mListCitys;
    AddressCheckAdapter addressCheckAdapter;
    boolean isIsgn = true;
    int signAddress = 1;//当前的级数
    String province,
            city,
            area,
            street;
    int address1 = 0;  //当前级数的对应的id
    int address2 = 0;
    int address3 = 0;
    int address4 = 0;


    @Override
    protected MerchantsListPresenter createPresenter() {
        return new MerchantsListPresenter();
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_merchants_list;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setTitleBar("商户");
        bundle = getIntent().getExtras();
        sign = bundle.getInt("sign");
        cityID = bundle.getInt("cityID");
        areaID = bundle.getInt("areaID");
        tvRegion.setText(LoginHelper.getCityData().getResult().getName());
        if (sign == 1) {
            service_type = bundle.getInt("service_type");
            mPresenter.onCooperationSreviceListData();
        }
        mList = new ArrayList<>();
//        rvNotice.setLayoutManager(new GridLayoutManager(getMe(), 2));


        StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
        //解决item跳动
        manager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        rvNotice.setLayoutManager(manager);
        rvNotice.setNestedScrollingEnabled(false);
        //创建适配器
        mAdapter = new MerchantsListAdapter(R.layout.activity_merchants_list_item, mList);
        //给RecyclerView设置适配器
        rvNotice.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //todo  商家列表 推荐 详情
                Bundle bundle = new Bundle();
                bundle.putInt("id", mAdapter.getItem(position).getId());
                $startActivity(BusinessHomeActivity.class, bundle);
            }
        });
        notDataView = NotDataView.notDataView(this, rvNotice, refreshLayout);
        initCheckData(1);
        getListData();

        initViewType();


        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    String key = etSearch.getText().toString().trim();
                    if (!TextUtils.isEmpty(key)) {
                        etSearch.clearFocus();
                        if (!TextUtils.isEmpty(key)) {
                            hideKeyboard(etSearch);
                            refreshLayout.autoRefresh();
                        } else {
                            refreshLayout.autoRefresh();
                        }
                    }
                }
                return false;
            }
        });

//        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
//            @Override
//            public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
//
//            }
//
//            @Override
//            public void onDrawerOpened(@NonNull View drawerView) {
//                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
//            }
//
//            @Override
//            public void onDrawerClosed(@NonNull View drawerView) {
//                drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
//            }
//
//            @Override
//            public void onDrawerStateChanged(int newState) {
//
//            }
//        });
    }


    private void initViewType() {
        mListRight = new ArrayList<>();
        LinearLayoutManager layoutManager2 = new LinearLayoutManager(getMe());
        layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager2.setSmoothScrollbarEnabled(true);
        layoutManager2.setAutoMeasureEnabled(true);
        tvTypes.setLayoutManager(layoutManager2);
        tvTypes.setNestedScrollingEnabled(false);
        //创建适配器
        typeRightAdapter = new TypeRigthBusinessAdapter(R.layout.drawer_type_right_item, mListRight);
        //给RecyclerView设置适配器
        tvTypes.setAdapter(typeRightAdapter);
    }

    @Override
    public void initRefreshLayout() {
        super.initRefreshLayout();
        RefreshHelper.initRefreshLayout(refreshLayout, new CustomRefreshListener() {
            @Override
            public void _onRefresh(RefreshLayout refreshLayout) {
                hideKeyboard(etSearch);
                pagehttp = 1;
                getListData();
            }

            @Override
            public void _onLoadMore(RefreshLayout refreshLayout) {
                hideKeyboard(etSearch);
                pagehttp++;
                if (null != mList) {
                    getListData();
                }
            }
        });
    }

    private void getListData() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("service_type", service_type);
        map.put("lon", LoginHelper.getLocationInfo().getLontitude());
        map.put("lat", LoginHelper.getLocationInfo().getLatitude());
        map.put("limit", pageNum);
        map.put("page", pagehttp);
        map.put("city", cityID);
        map.put("area", areaID);
        map.put("fraction", fractionChek);
        map.put("juli", "1");
        map.put("want", "");
        map.put("title", etSearch.getText().toString().trim());
        mPresenter.onBusinessListData(LoginHelper.getLonginData().getResult(), map);
    }

    /**
     * 优惠劵
     */
    private void showAddress() {
        if (popupWindowAddress != null && popupWindowAddress.isShowing()) return;
        View upView = LayoutInflater.from(getMe()).inflate(R.layout.pw_address, null);
        //测量View的宽高
        CommonUtil.measureWidthAndHeight(upView);
        popupWindowAddress = new CommonPopupWindow.Builder(getMe())
                .setView(R.layout.pw_address)
                .setWidthAndHeight(ViewGroup.LayoutParams.MATCH_PARENT, upView.getMeasuredHeight())
                .setBackGroundLevel(0.5f)//取值范围0.0f-1.0f 值越小越暗
                .setAnimationStyle(R.style.AnimUp)
                .setViewOnclickListener(this)
                .create();
        popupWindowAddress.showAtLocation(findViewById(android.R.id.content), Gravity.BOTTOM, 0, 0);
    }

    @Override
    public void getChildView(View view, int layoutResId) {
        switch (layoutResId) {
            //todo
            case R.layout.pw_address:
                RecyclerView rvCoupon = view.findViewById(R.id.recyclerView);
                rvCoupon.setLayoutManager(new LinearLayoutManager(getMe()));
                TextView tv_1 = view.findViewById(R.id.tv_1);
                TextView tv_2 = view.findViewById(R.id.tv_2);
                TextView tv_3 = view.findViewById(R.id.tv_3);
                TextView tv_4 = view.findViewById(R.id.tv_4);

                if (!TextUtils.isEmpty(province)) {
                    tv_1.setText(province);
                    tv_1.setVisibility(View.VISIBLE);
                }
                if (!TextUtils.isEmpty(city)) {
                    tv_2.setVisibility(View.VISIBLE);
                    tv_2.setText(city);
                }

                if (!TextUtils.isEmpty(area)) {
                    tv_3.setVisibility(View.VISIBLE);
                    tv_3.setText(area);
                }

                if (!TextUtils.isEmpty(street)) {
                    tv_4.setVisibility(View.VISIBLE);
                    tv_4.setText(street);
                }

                tv_1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(tv_2.getText().toString().toString())) {
                            tv_1.setText("");
                            tv_1.setVisibility(View.GONE);
                            signAddress = 1;
                            address1 = 0;
                            province = "";
                            tvRegion.setText(LoginHelper.getCityData().getResult().getName());
                            isIsgn = false;
                            mPresenter.onCityListData(1);
                        }

                    }
                });
                tv_2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (TextUtils.isEmpty(tv_3.getText().toString().toString())) {
                            tv_2.setText("");
                            tv_2.setVisibility(View.GONE);
                            address2 = 0;
                            signAddress = 2;
                            city = "";
                            isIsgn = false;
                            mPresenter.onCityListData(address1);
                        }
                    }
                });
                tv_3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (TextUtils.isEmpty(tv_4.getText().toString().toString())) {
                            tv_3.setText("");
                            tv_3.setVisibility(View.GONE);
                            signAddress = 3;
                            address3 = 0;
                            area = "";
                            isIsgn = false;
                            mPresenter.onCityListData(address2);
                        }
                    }
                });
                tv_4.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tv_4.setText("");
                        tv_4.setVisibility(View.GONE);
                        signAddress = 4;
                        address4 = 0;
                        street = "";
                        isIsgn = false;
                        mPresenter.onCityListData(address3);
                    }
                });
                //创建适配器
                addressCheckAdapter = new AddressCheckAdapter(R.layout.pw_address_item, mListCitys);
                //给RecyclerView设置适配器
                rvCoupon.setAdapter(addressCheckAdapter);
                addressCheckAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        if (signAddress == 1) {
                            tv_1.setVisibility(View.VISIBLE);
                            tv_1.setText(addressCheckAdapter.getItem(position).getName());
                            address1 = addressCheckAdapter.getItem(position).getId();
                            signAddress = 2;
                            province = tv_1.getText().toString().trim();
                            isIsgn = false;
                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        } else if (signAddress == 2) {
                            tv_2.setVisibility(View.VISIBLE);
                            tv_2.setText(addressCheckAdapter.getItem(position).getName());
                            address2 = addressCheckAdapter.getItem(position).getId();
                            city = tv_2.getText().toString().trim();
                            signAddress = 3;
                            isIsgn = false;
                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        } else if (signAddress == 3) {
                            tv_3.setVisibility(View.VISIBLE);
                            tv_3.setText(addressCheckAdapter.getItem(position).getName());
                            address3 = addressCheckAdapter.getItem(position).getId();
                            area = tv_3.getText().toString().trim();
//                            etAdd.setText(province + city + area);
                            signAddress = 4;
                            isIsgn = false;
                            tvRegion.setText(area);
                            popupWindowAddress.dismiss();
                            cityID = address2;
                            areaID = address3;
                            refreshLayout.autoRefresh();

//                            mPresenter.onCityListData(addressCheckAdapter.getItem(position).getId());
                        }
//                        else {
//                            tv_4.setVisibility(View.VISIBLE);
//                            tv_4.setText(addressCheckAdapter.getItem(position).getName());
//                            address4 = addressCheckAdapter.getItem(position).getId();
//                            street = tv_4.getText().toString().trim();
////                            tvAddress.setText(province + city + area + street);
//                            tvRegion.setText(area);
//                            popupWindowAddress.dismiss();
//                        }

                    }
                });

                view.findViewById(R.id.tv_btn_colce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindowAddress.dismiss();
                    }
                });
                break;
        }
    }

    @Override
    public void onReLoggedIn(String msg) {
        RxToast.error(msg);
        LoginHelper.againGoToLoginActivity(getMe());
    }

    @Override
    public void onError(String msg) {
        RxToast.error(msg);
    }

    @Override
    public Context _getContext() {
        return getMe();
    }

    @Override
    public void onCooperationSreviceListSuccess(CooperationSreviceListBean bean) {
        cooperationSreviceListBean = bean;
        mListRight = bean.getResult();
        if (service_type > 0) {
            for (int i = 0; i < mListRight.size(); i++) {
                for (int j = 0; j < mListRight.get(i).getChildren().size(); j++) {
                    if (service_type == mListRight.get(i).getChildren().get(j).getId()) {
                        mListRight.get(i).setCheck(true);
                        mListRight.get(i).getChildren().get(j).setCheck(true);
                    }
                }
            }
            typeRightAdapter.replaceData(bean.getResult());
        } else {
            typeRightAdapter.replaceData(bean.getResult());
            drawerLayout.openDrawer(Gravity.RIGHT);
        }
    }

    @Override
    public void onBusinessListSuccess(BusinessListBean bean) {
        RefreshHelper.finishRefresh(refreshLayout, pagehttp);
        if (pagehttp == 1) {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.replaceData(bean.getResult().getData());
            } else {
                mList.clear();
                mAdapter.replaceData(mList);
                mAdapter.setEmptyView(notDataView);
            }
        } else {
            if (bean.getResult() != null && bean.getResult().getData().size() > 0) {
                mAdapter.addData(bean.getResult().getData());
            }

        }
    }

    @Override
    public void onProvinceListSuccess(AddressProvinceListBean bean) {
        if (bean.getResult() != null && bean.getResult().size() > 0) {
            mListCitys = bean.getResult();
            showAddress();
        }
    }

    @Override
    public void onCityListSuccess(AddressProvinceListBean bean) {
        if (bean.getResult() != null && bean.getResult().size() > 0) {
            mListCitys = bean.getResult();
            addressCheckAdapter.replaceData(mListCitys);
//            if (!isIsgn)
//                addressCheckAdapter.replaceData(mListCitys);
//            else showAddress();
        }

    }


    private void initCheckData(int index) {
        switch (index) {
            case 1:
                tvAll.setTextColor(getResources().getColor(R.color.main_color));
                tvRegion.setTextColor(getResources().getColor(R.color.text_666666));
                tvComment.setTextColor(getResources().getColor(R.color.text_666666));
                tvType.setTextColor(getResources().getColor(R.color.text_666666));
                break;
            case 2:
                tvAll.setTextColor(getResources().getColor(R.color.text_666666));
                tvRegion.setTextColor(getResources().getColor(R.color.main_color));
                tvComment.setTextColor(getResources().getColor(R.color.text_666666));
                tvType.setTextColor(getResources().getColor(R.color.text_666666));
                break;
            case 3:
                tvAll.setTextColor(getResources().getColor(R.color.text_666666));
                tvRegion.setTextColor(getResources().getColor(R.color.text_666666));
                tvComment.setTextColor(getResources().getColor(R.color.main_color));
                tvType.setTextColor(getResources().getColor(R.color.text_666666));
                if (fractionChek == 1) {
                    fractionChek = 2;
                    imgCheck.setImageResource(R.drawable.shang_false);
                } else {
                    fractionChek = 1;
                    imgCheck.setImageResource(R.drawable.shang_true);
                }
                break;
            case 4:
                tvAll.setTextColor(getResources().getColor(R.color.text_666666));
                tvRegion.setTextColor(getResources().getColor(R.color.text_666666));
                tvComment.setTextColor(getResources().getColor(R.color.text_666666));
                tvType.setTextColor(getResources().getColor(R.color.main_color));
                break;
        }
    }


    @Override
    public void leftFinish() {
        super.leftFinish();
        hideKeyboard(etSearch);
        finish();
    }


    @OnClick({R.id.ll_btn_all, R.id.ll_btn_region, R.id.ll_btn_comment, R.id.ll_btn_type, R.id.ll_btn_add})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_btn_all:
                initCheckData(1);
                refreshLayout.autoRefresh();
                break;
            case R.id.ll_btn_region:
                initCheckData(2);
                //省
                hideKeyboard(etSearch);
//                isIsgn = true;
//                if (!TextUtils.isEmpty(tvAddress.getText().toString().trim())) {
//                    signAddress = 4;
//                    mPresenter.onCityListData(address3);
//                } else {
//                    signAddress = 1;
//                    mPresenter.onProvinceListData();
//                }
                signAddress = 1;
                mPresenter.onProvinceListData();

                break;
            case R.id.ll_btn_comment:
                initCheckData(3);
                refreshLayout.autoRefresh();
                break;
            case R.id.ll_btn_type:
                initCheckData(4);
//                getListData();
                //分类
                if (cooperationSreviceListBean != null)
                    drawerLayout.openDrawer(Gravity.RIGHT);
                else mPresenter.onCooperationSreviceListData();

                break;
            case R.id.ll_btn_add:

//                RxToast.success("发布服务");
                break;
        }
    }


    class TypeRigthBusinessAdapter extends BaseQuickAdapter<CooperationSreviceListBean.ResultBean, BaseViewHolder> {

        public TypeRigthBusinessAdapter(int layoutResId, @Nullable List<CooperationSreviceListBean.ResultBean> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, final CooperationSreviceListBean.ResultBean item) {
            helper.setText(R.id.tv_title, item.getTitle());
            RecyclerView rv_data_items = helper.getView(R.id.rv_type_item);
            rv_data_items.setLayoutManager(new GridLayoutManager(getMe(), 3));
            rv_data_items.setNestedScrollingEnabled(false);
            //创建适配器
            LoggerUtils.e("看看:" + item.isCheck());
            SreviceTypeToAdapter typeRigthAdapter = new SreviceTypeToAdapter(R.layout.drawer_type_right_item_s, item.getChildren(), item.isCheck());
            //给RecyclerView设置适配器
            rv_data_items.setAdapter(typeRigthAdapter);
            typeRigthAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    //todo
                    for (int i = 0; i < mListRight.size(); i++) {
                        if (item.getId() == mListRight.get(i).getId())
                            mListRight.get(i).setCheck(true);
                        else mListRight.get(i).setCheck(false);
                    }
                    for (int i = 0; i < item.getChildren().size(); i++) {
                        if (i == position) {
                            item.getChildren().get(i).setCheck(true);
                        } else item.getChildren().get(i).setCheck(false);
                    }
                    service_type = typeRigthAdapter.getItem(position).getId();
                    typeRightAdapter.notifyDataSetChanged();
                    drawerLayout.closeDrawer(Gravity.RIGHT);
                    refreshLayout.autoRefresh();

                }
            });
        }


    }
}
